import * as mongoose from 'mongoose';

import fastFormatTimeSchema from './base';
import paginate from './plugins/paginate';
import autoPopulateSubs from './plugins/auto-populate-subs';

const { Schema } = mongoose;

const contactSchema = new Schema(
  {
    firstName: Schema.Types.String,
    lastName: Schema.Types.String,
    email: Schema.Types.String,
    phone: Schema.Types.String,
    companyName: Schema.Types.String,
    companyType: {
      type: Schema.Types.ObjectId,
      ref: 'dictionary',
    },
    country: {
      type: Schema.Types.ObjectId,
      ref: 'dictionary',
    },
    locale: {
      type: Schema.Types.ObjectId,
      ref: 'dictionary',
    },
    subscribe: {
      type: Schema.Types.Number,
      enum: [0, 1],
    },
    message: Schema.Types.String,
    ...fastFormatTimeSchema(),
  },
  {
    versionKey: false,
    timestamps: true,
    toJSON: {
      getters: true,
      transform(doc, ret) {
        ret.id = ret._id;
        ret.blog = Boolean(ret.blog);
        ret.product = Boolean(ret.product);
        delete ret._id;
      },
    },
    toObject: {
      getters: true,
      transform(doc, ret) {
        ret.id = ret._id;
        ret.blog = Boolean(ret.blog);
        ret.product = Boolean(ret.product);
        delete ret._id;
      },
    },
  },
);

export default paginate(
  autoPopulateSubs({
    schema: contactSchema,
    methods: ['find', 'findOne'],
    populates: [
      {
        path: 'companyType',
        select: 'id value name',
      },
      {
        path: 'country',
        select: 'id value name',
      },
      {
        path: 'locale',
        select: 'id value name',
      },
    ],
  }),
);
